package com.example.spider.config;

import com.example.spider.proxy.SpiderContextHolder;
import com.example.spider.util.SkipHttpsVerifyUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

/**
 * 可代理的
 */
@Getter
@Setter
@Component
public class ProxyableClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

    public ProxyableClientHttpRequestFactory() {
        setConnectTimeout(20_000);
        setReadTimeout(20_000);
    }

    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        SkipHttpsVerifyUtil.trustAllCerts(connection);
        super.prepareConnection(connection, httpMethod);
    }

    protected HttpURLConnection openConnection(URL url, @Nullable Proxy proxy) throws IOException {
        // 前置增强：使用代理
        Proxy realProxy = SpiderContextHolder.getProxyInfo().toProxy();
        return super.openConnection(url, realProxy);
    }

}
